<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>JS-Qrcode</title>
</head>
<style>
	div{
		margin-top: 20px;
	}
</style>
<body>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
	<script type="text/javascript" src="jquery.qrcode.min.js"></script>

	<h1>JS生成二维码和下载</h1>  
	<div>  
		<label for="qr_text">二维码生成内容：</label>        
		<input id="qr_text" type="text" value="http://www.baidu.com/" style="width:200px;" />   
	</div>  
	<div>
		<label for="">宽度：</label>
		<input id="qr_width" type="text" value="180" style="width:200px;" />
	</div>
	<div>
		<label for="">高度：</label>
		<input id="qr_height" type="text" value="180" style="width:200px;" />
	</div>
	<div>
		<label for="">背景颜色：</label>
		<input id="qr_background" type="text" value="#ffffff" style="width:200px;" />
	</div>
	<div>
		<label for="">前景颜色 ：</label>
		<input id="qr_foreground" type="text" value="#000000" style="width:200px;" />
	</div>

	<div>
		<button id="qr_btn" value="button">生成</button>
		<button id="downQrcode" value="button">下载二维码</button>
	</div>
	<hr>
	<div id="qr_container" style="margin-top: 20px;"></div>  
	<div id="imgDiv"></div>
<script>  
	$(document).ready(function(){
	    // 点击生成二维码  
	    $('#qr_btn').click(function(){    
	    	/*如果已生成过二维码，则删除二维码img图片和canvas，重新生成；反之，则直接生成二维码*/  
	    	if($('#imgDiv:has(img)').length!=0){  
	    		$('#imgDiv img').remove();  
	    		$('canvas').remove();  
	    		createQr();  
	    	}else{  
	    		createQr(); 
	    	}  
	    });

	    $('#downQrcode').click(function(){
	    	downQrcode();
	    });

	    // 生成二维码  
	    function createQr(){  
	    	document.createElement('canvas').getContext('2d');  
	    	var valText = $('#qr_text').val();  
	    	var valWidth = ($('#qr_width').val() != '') ? $('#qr_width').val() : 180;  
	    	var valHeight = ($('#qr_height').val() != '') ? $('#qr_height').val() :180;  
	    	var valBackground = ($('#qr_background').val() != '') ? $('#qr_background').val() : '#ffffff';  
	    	var valForeground = ($('#qr_foreground').val() != '') ? $('#qr_foreground').val() : '#000000';  

	        // 采用正则表达式判断输入的内容是否是中文  
	        var reg=/^[\u0391-\uFFE5]+$/;   
	        if(valText!=""&&!reg.test(valText)){   
	            // 如果不是中文，直接将输入的内容转换成二维码  
	            $('#qr_container').qrcode({render:"canvas",height:valHeight, width:valWidth,correctLevel:0,text:valText,background:valBackground,foreground:valForeground});  
	        }else{  
	            // 如果是中文，直接将输入的内容字符串转换成UTF-8，然后再转换成二维码  
	            $('#qr_container').qrcode({render:"canvas",height:valHeight, width:valWidth,correctLevel:0,text:utf16to8(valText),background:valBackground,foreground:valForeground});  
	        }  
	    }

	    //下载二维码
	    var downQrcode = function(){
	    	 //获取网页中的canvas对象  
	    	 var mycanvas =document.getElementsByTagName('canvas')[0];
	    	 if(!mycanvas){
	    	 	alert('先生成二维码再下载');
	    	 	return false;
	    	 }
	    	 var type = 'png';
	        //将转换后的img标签插入到html中  
	        // var imgData = convertCanvasToImage(mycanvas1);  
	        // $('#imgDiv').append(img);//imgDiv表示你要插入的容器id  
	        var imgData = mycanvas.toDataURL(type);
	        imgData = imgData.replace(_fixType(type),'image/octet-stream');
	        // 下载后的问题名
	        var filename = 'baidufe_' + (new Date()).getTime() + '.' + type;
			// download
			saveFile(imgData,filename);
		}

	    // 字符编码  
	    function utf16to8(str) {    
	    	var out, i, len, c;    
	    	out = "";    
	    	len = str.length;    
	    	for(i = 0; i < len; i++) {    
	    		c = str.charCodeAt(i);    
	    		if ((c >= 0x0001) && (c <= 0x007F)) {    
	    			out += str.charAt(i);    
	    		} else if (c > 0x07FF) {    
	    			out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));    
	    			out += String.fromCharCode(0x80 | ((c >>  6) & 0x3F));    
	    			out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));    
	    		} else {    
	    			out += String.fromCharCode(0xC0 | ((c >>  6) & 0x1F));    
	    			out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));    
	    		}    
	    	}    
	    	return out;    
	    }  

	    //从canvas中提取图片image  
	    function convertCanvasToImage(canvas) { 
	        //新Image对象，可以理解为DOM  
	        var image = new Image();  
	        // canvas.toDataURL 返回的是一串Base64编码的URL  
	        // 指定格式PNG  
	        image.src = canvas.toDataURL("image/png");  
	        return image;  
	    }

	    // 把image 转换为 canvas对象  
	    function convertImageToCanvas(image) {  
		    // 创建canvas DOM元素，并设置其宽高和图片一样   
		    var canvas = document.createElement("canvas");  
		    canvas.width = image.width;  
		    canvas.height = image.height;  
		    // 坐标(0,0) 表示从此处开始绘制，相当于偏移。  
		    canvas.getContext("2d").drawImage(image, 0, 0);  

		    return canvas;  
		}

		var _fixType = function(type) {
			type = type.toLowerCase().replace(/jpg/i, 'jpeg');
			var r = type.match(/png|jpeg|bmp|gif/)[0];
			return 'image/' + r;
		};

		var saveFile = function(data, filename){
			var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
			save_link.href = data;
			save_link.download = filename;

			var event = document.createEvent('MouseEvents');
			//这个方法未来不会支持
			event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
			save_link.dispatchEvent(event);
		};  
	});  
</script>
</body>
</html>